<template>
  <div class="user-management">
    <div class="toolbar">
      <el-input
        v-model="searchQuery"
        placeholder="搜索用户..."
        clearable
        @keyup.enter="searchUsers"
        style="width: 200px; margin-right: 10px;"
      >
        <template #append>
          <el-button :icon="Search" @click="searchUsers"></el-button>
        </template>
      </el-input>
      <el-button type="primary" @click="showAddUserDialog">添加用户</el-button>
    </div>

    <div v-if="loading" class="loading-container">
      <el-skeleton :rows="6" animated />
    </div>
    <div v-else-if="users.length === 0" class="empty-container">
      <el-empty description="暂无用户" />
    </div>
    <el-table v-else :data="users" style="width: 100%">
      <el-table-column prop="username" label="用户名" min-width="120"></el-table-column>
      <el-table-column prop="email" label="邮箱" min-width="180"></el-table-column>
      <el-table-column label="角色" width="100">
        <template #default="scope">
          <el-tag :type="scope.row.is_admin ? 'danger' : 'info'">
            {{ scope.row.is_admin ? '管理员' : '普通用户' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="注册时间" width="180">
        <template #default="scope">
          {{ new Date(scope.row.created_at).toLocaleString() }}
        </template>
      </el-table-column>
      <el-table-column label="状态" width="100">
        <template #default="scope">
          <el-switch
            v-model="scope.row.is_active"
            @change="(val) => toggleUserStatus(scope.row.id, val)"
            :loading="scope.row.statusLoading"
          />
        </template>
      </el-table-column>
      <el-table-column label="操作" width="250">
        <template #default="scope">
          <el-button size="small" @click="showEditUserDialog(scope.row)">编辑</el-button>
          <el-button 
            size="small" 
            type="success" 
            @click="resetPassword(scope.row.id)"
          >重置密码</el-button>
          <el-button 
            size="small" 
            type="danger" 
            @click="deleteUser(scope.row.id)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination-container" v-if="total > 0">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50]"
        :total="total"
        layout="total, sizes, prev, pager, next"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 添加/编辑用户对话框 -->
    <el-dialog 
      v-model="dialogVisible" 
      :title="editingUser ? '编辑用户' : '添加用户'"
      width="40%"
    >
      <el-form 
        :model="userForm" 
        :rules="userRules" 
        ref="userFormRef"
        label-width="80px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="userForm.username" :disabled="!!editingUser"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="userForm.email"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="!editingUser">
          <el-input v-model="userForm.password" type="password"></el-input>
        </el-form-item>
        <el-form-item label="角色">
          <el-switch
            v-model="userForm.is_admin"
            active-text="管理员"
            inactive-text="普通用户"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitUserForm" :loading="submitting">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { Search } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// 搜索和分页状态
const searchQuery = ref('')
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 数据状态
const loading = ref(true)
const users = ref([])

// 表单状态
const dialogVisible = ref(false)
const submitting = ref(false)
const userFormRef = ref(null)
const editingUser = ref(null)

const userForm = reactive({
  username: '',
  email: '',
  password: '',
  is_admin: false
})

const userRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
  ]
}

// 初始化
onMounted(() => {
  fetchUsers()
})

// 获取用户列表
async function fetchUsers() {
  loading.value = true
  try {
    // 这里替换为实际的API调用
    // const response = await axios.get('/api/admin/users', {
    //   params: {
    //     page: currentPage.value,
    //     size: pageSize.value,
    //     query: searchQuery.value
    //   }
    // })
    
    // 模拟数据
    await new Promise(resolve => setTimeout(resolve, 500))
    users.value = Array.from({ length: 10 }, (_, i) => ({
      id: i + 1,
      username: `user${i + 1}`,
      email: `user${i + 1}@example.com`,
      is_admin: i === 0,
      is_active: true,
      created_at: new Date().getTime() - Math.floor(Math.random() * 10000000)
    }))
    
    total.value = 100
  } catch (error) {
    console.error('Failed to fetch users:', error)
    ElMessage.error('获取用户列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索用户
function searchUsers() {
  currentPage.value = 1
  fetchUsers()
}

// 显示添加用户对话框
function showAddUserDialog() {
  editingUser.value = null
  userForm.username = ''
  userForm.email = ''
  userForm.password = ''
  userForm.is_admin = false
  dialogVisible.value = true
}

// 显示编辑用户对话框
function showEditUserDialog(user) {
  editingUser.value = user
  userForm.username = user.username
  userForm.email = user.email
  userForm.is_admin = user.is_admin
  dialogVisible.value = true
}

// 提交用户表单
async function submitUserForm() {
  if (!userFormRef.value) return
  
  await userFormRef.value.validate(async (valid) => {
    if (valid) {
      submitting.value = true
      try {
        if (editingUser.value) {
          // 编辑用户
          // await axios.put(`/api/admin/users/${editingUser.value.id}`, userForm)
          await new Promise(resolve => setTimeout(resolve, 500))
          ElMessage.success('用户更新成功')
        } else {
          // 添加用户
          // await axios.post('/api/admin/users', userForm)
          await new Promise(resolve => setTimeout(resolve, 500))
          ElMessage.success('用户添加成功')
        }
        
        dialogVisible.value = false
        fetchUsers()
      } catch (error) {
        console.error('Failed to submit user form:', error)
        ElMessage.error(editingUser.value ? '更新用户失败' : '添加用户失败')
      } finally {
        submitting.value = false
      }
    }
  })
}

// 切换用户状态
async function toggleUserStatus(userId, status) {
  try {
    // await axios.put(`/api/admin/users/${userId}/status`, { status })
    await new Promise(resolve => setTimeout(resolve, 500))
    ElMessage.success(`用户状态已${status ? '启用' : '禁用'}`)
  } catch (error) {
    console.error('Failed to toggle user status:', error)
    ElMessage.error('更新用户状态失败')
    // 回滚状态
    const user = users.value.find(u => u.id === userId)
    if (user) {
      user.is_active = !status
    }
  }
}

// 重置密码
async function resetPassword(userId) {
  try {
    await ElMessageBox.confirm('确定要重置该用户的密码吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    // await axios.post(`/api/admin/users/${userId}/reset-password`)
    await new Promise(resolve => setTimeout(resolve, 500))
    ElMessage.success('密码重置成功')
  } catch (error) {
    if (error !== 'cancel') {
      console.error('Failed to reset password:', error)
      ElMessage.error('密码重置失败')
    }
  }
}

// 删除用户
async function deleteUser(userId) {
  try {
    await ElMessageBox.confirm('确定要删除该用户吗？此操作不可恢复。', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    // await axios.delete(`/api/admin/users/${userId}`)
    await new Promise(resolve => setTimeout(resolve, 500))
    
    users.value = users.value.filter(user => user.id !== userId)
    total.value--
    
    ElMessage.success('用户删除成功')
  } catch (error) {
    if (error !== 'cancel') {
      console.error('Failed to delete user:', error)
      ElMessage.error('删除用户失败')
    }
  }
}

// 分页处理
function handleSizeChange(size) {
  pageSize.value = size
  fetchUsers()
}

function handleCurrentChange(page) {
  currentPage.value = page
  fetchUsers()
}
</script>

<style scoped>
.user-management {
  padding: 20px;
}

.toolbar {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
}

.loading-container,
.empty-container {
  padding: 40px 0;
  text-align: center;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}
</style> 